import torch
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence

#一个RNN读取数据压缩和逆向填充的小demo

def describe(x):
    print("Type:{}".format(x.type()))
    print("Shape/size:{}".format(x.shape))
    print("Values:\n{}".format(x))

abcd_padded=torch.tensor([1,2,3,4],dtype=torch.float32)
efg_padded=torch.tensor([5,6,7,0],dtype=torch.float32)
h_padded=torch.tensor([8,0,0,0],dtype=torch.float32)

padded_tensor=torch.stack([abcd_padded,efg_padded,h_padded])

describe(padded_tensor)

lengths=[4,3,1]
#RNN读取数据的方式，网络每次吃进去一组同样时间步的数据，压缩无效的0值
packed_tensor=pack_padded_sequence(padded_tensor,lengths,batch_first=True)
print(packed_tensor)

#pack_padded_sequence的逆向操作，将压缩后的序列再填充回来
unpacked_tensor,unpacked_lengths=pad_packed_sequence(packed_tensor,batch_first=True)
describe(unpacked_tensor)
describe(unpacked_lengths)
